package com.ken.apollo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ken.apollo.commons.result.R;
import com.ken.apollo.domain.bo.ContactInquiryBo;
import com.ken.apollo.domain.query.ContactInquiryQuery;
import com.ken.apollo.domain.vo.ContactInquiryVo;
import com.ken.apollo.service.ContactInquiryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;

/**
 * 联系咨询控制器
 *
 * @author Ken
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/api/contact")
public class ContactInquiryController {

    @Autowired
    private ContactInquiryService contactInquiryService;

    /**
     * 提交联系咨询
     */
    @PostMapping("/submit")
    public R<Boolean> submitInquiry(@RequestBody ContactInquiryBo bo, HttpServletRequest request) {
        try {
            // 验证至少填写了一个字段
            if ((bo.getName() == null || bo.getName().trim().isEmpty()) &&
                (bo.getEmail() == null || bo.getEmail().trim().isEmpty()) &&
                (bo.getCompany() == null || bo.getCompany().trim().isEmpty()) &&
                (bo.getMessage() == null || bo.getMessage().trim().isEmpty())) {
                return R.fail("Please fill in at least one field");
            }
            
            // 获取客户端IP地址
            String ipAddress = getClientIpAddress(request);
            bo.setIpAddress(ipAddress);
            
            // 获取用户代理信息
            String userAgent = request.getHeader("User-Agent");
            bo.setUserAgent(userAgent);
            
            Boolean result = contactInquiryService.submitInquiry(bo);
            
            if (result) {
                log.info("联系咨询提交成功，邮箱: {}, IP: {}", bo.getEmail(), ipAddress);
                return R.success(result, "Thank you for your inquiry! We'll get back to you within 24 hours.");
            } else {
                return R.fail("Failed to submit inquiry. Please try again.");
            }
        } catch (Exception e) {
            log.error("提交联系咨询失败", e);
            return R.fail("An error occurred while submitting your inquiry. Please try again later.");
        }
    }

    /**
     * 分页查询联系咨询列表
     */
    @GetMapping("/list")
    public R<IPage<ContactInquiryVo>> queryPage(ContactInquiryQuery query) {
        try {
            IPage<ContactInquiryVo> result = contactInquiryService.queryPage(query);
            return R.success(result);
        } catch (Exception e) {
            log.error("查询联系咨询列表失败", e);
            return R.fail("Failed to query contact inquiries");
        }
    }

    /**
     * 查询联系咨询列表（不分页）
     */
    @GetMapping("/all")
    public R<List<ContactInquiryVo>> queryAll(ContactInquiryQuery query) {
        try {
            List<ContactInquiryVo> result = contactInquiryService.queryList(query);
            return R.success(result);
        } catch (Exception e) {
            log.error("查询联系咨询列表失败", e);
            return R.fail("Failed to query contact inquiries");
        }
    }

    /**
     * 根据ID查询联系咨询详情
     */
    @GetMapping("/detail/{id}")
    public R<ContactInquiryVo> queryById(@PathVariable Long id) {
        try {
            ContactInquiryVo result = contactInquiryService.queryById(id);
            if (result != null) {
                return R.success(result);
            } else {
                return R.fail("Contact inquiry not found");
            }
        } catch (Exception e) {
            log.error("查询联系咨询详情失败，ID: {}", id, e);
            return R.fail("Failed to query contact inquiry details");
        }
    }

    /**
     * 更新联系咨询状态
     */
    @PutMapping("/status/{id}")
    public R<Boolean> updateStatus(@PathVariable Long id, @RequestParam String status) {
        try {
            Boolean result = contactInquiryService.updateStatus(id, status);
            if (result) {
                return R.success(result, "Status updated successfully");
            } else {
                return R.fail("Failed to update status");
            }
        } catch (Exception e) {
            log.error("更新联系咨询状态失败，ID: {}", id, e);
            return R.fail("Failed to update status");
        }
    }

    /**
     * 批量更新联系咨询状态
     */
    @PutMapping("/status/batch")
    public R<Boolean> batchUpdateStatus(@RequestParam List<Long> ids, @RequestParam String status) {
        try {
            Boolean result = contactInquiryService.batchUpdateStatus(ids, status);
            if (result) {
                return R.success(result, "Status updated successfully");
            } else {
                return R.fail("Failed to update status");
            }
        } catch (Exception e) {
            log.error("批量更新联系咨询状态失败", e);
            return R.fail("Failed to update status");
        }
    }

    /**
     * 删除联系咨询
     */
    @DeleteMapping("/{id}")
    public R<Boolean> deleteById(@PathVariable Long id) {
        try {
            Boolean result = contactInquiryService.deleteById(id);
            if (result) {
                return R.success(result, "Contact inquiry deleted successfully");
            } else {
                return R.fail("Failed to delete contact inquiry");
            }
        } catch (Exception e) {
            log.error("删除联系咨询失败，ID: {}", id, e);
            return R.fail("Failed to delete contact inquiry");
        }
    }

    /**
     * 批量删除联系咨询
     */
    @DeleteMapping("/batch")
    public R<Boolean> batchDelete(@RequestParam List<Long> ids) {
        try {
            Boolean result = contactInquiryService.batchDelete(ids);
            if (result) {
                return R.success(result, "Contact inquiries deleted successfully");
            } else {
                return R.fail("Failed to delete contact inquiries");
            }
        } catch (Exception e) {
            log.error("批量删除联系咨询失败", e);
            return R.fail("Failed to delete contact inquiries");
        }
    }

    /**
     * 获取状态统计
     */
    @GetMapping("/statistics/status")
    public R<List<ContactInquiryVo>> getStatusStatistics() {
        try {
            List<ContactInquiryVo> result = contactInquiryService.getStatusStatistics();
            return R.success(result);
        } catch (Exception e) {
            log.error("获取状态统计失败", e);
            return R.fail("Failed to get status statistics");
        }
    }

    /**
     * 获取主题统计
     */
    @GetMapping("/statistics/subject")
    public R<List<ContactInquiryVo>> getSubjectStatistics() {
        try {
            List<ContactInquiryVo> result = contactInquiryService.getSubjectStatistics();
            return R.success(result);
        } catch (Exception e) {
            log.error("获取主题统计失败", e);
            return R.fail("Failed to get subject statistics");
        }
    }

    /**
     * 获取待处理数量
     */
    @GetMapping("/count/pending")
    public R<Long> getPendingCount() {
        try {
            Long result = contactInquiryService.getPendingCount();
            return R.success(result);
        } catch (Exception e) {
            log.error("获取待处理数量失败", e);
            return R.fail("Failed to get pending count");
        }
    }

    /**
     * 获取今日新增数量
     */
    @GetMapping("/count/today")
    public R<Long> getTodayCount() {
        try {
            Long result = contactInquiryService.getTodayCount();
            return R.success(result);
        } catch (Exception e) {
            log.error("获取今日新增数量失败", e);
            return R.fail("Failed to get today count");
        }
    }

    /**
     * 获取客户端真实IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
